package com.alpha.realife.utils;

import io.netty.channel.ChannelOutboundInvoker;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.net.HttpURLConnection;

/**
 * @version V1.0
 * @author: Albert
 * @date: 2020/7/1 15:27
 * @description:
 */
@Slf4j
public class ResourceCloseUtils {
    private ResourceCloseUtils() {
    }

    /**
     * 传接口, 不传实现类!!!
     *
     * @param resources
     */
    public static void close(AutoCloseable... resources) {
        System.out.println("ResourceCloseUtils void close(AutoCloseable... resources)...");
        for (AutoCloseable resource : resources) {
            if (resource != null) {
                try {
                    resource.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * ChannelOutboundInvoker close
     *
     * @param channels
     */
    public static void close(ChannelOutboundInvoker... channels) {
        System.out.println("ResourceCloseUtils void close(ChannelOutboundInvoker... channels)...");
        for (ChannelOutboundInvoker channel : channels) {
            if (channel != null) {
                channel.close();
            }
        }
    }

    /**
     * ChannelOutboundInvoker disconnect
     *
     * @param channels
     */
    public static void disconnect(ChannelOutboundInvoker... channels) {
        System.out.println("ResourceCloseUtils void disconnect(ChannelOutboundInvoker... channels)...");
        for (ChannelOutboundInvoker channel : channels) {
            if (channel != null) {
                channel.disconnect();
            }
        }
    }


    /**
     * 处理 EventExecutorGroup shutdownGracefully
     *
     * @param eventExecutorGroups
     */
    public static void shutdownGracefully(EventExecutorGroup... eventExecutorGroups) {
        System.out.println("ResourceCloseUtils void shutdownGracefully(EventExecutorGroup... eventExecutorGroups)...");
        for (EventExecutorGroup eventExecutorGroup : eventExecutorGroups) {
            if (eventExecutorGroup != null) {
                eventExecutorGroup.shutdownGracefully();
            }
        }
    }

    /**
     * 传父类,不传子类???
     *
     * @param urlConnections
     */
    public static void disconnect(HttpURLConnection... urlConnections) {
        System.out.println("ResourceCloseUtils void disconnect(HttpURLConnection... urlConnections)...");
        for (HttpURLConnection urlConnection : urlConnections) {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}